<template>
  <div ref="containerRef"></div>
</template>

<script setup lang="ts">
import {
  AmbientLight,
  Box3,
  Object3D,
  PerspectiveCamera,
  PointLight,
  Scene,
  Vector3,
  WebGLRenderer,
  MeshBasicMaterial,
  EdgesGeometry,
  LineSegments,
  LineBasicMaterial,
} from 'three'
// import Stats from 'three/examples/jsm/libs/stats.module.js'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js'
import { onMounted, ref } from 'vue'

const props = defineProps({
  fbxSrc: {
    type: String,
    default: '',
  },
  mtlSrc: {
    type: String,
    default: '',
  },
})

const containerRef = ref()

let camera: PerspectiveCamera, scene, renderer

onMounted(() => {
  init()
})

function init() {
  camera = new PerspectiveCamera(
    45,
    window.innerWidth / window.innerHeight,
    0.1,
    20,
  )
  camera.position.z = 2.5

  scene = new Scene()

  const ambientLight = new AmbientLight(0xffffff, 1)
  scene.add(ambientLight)

  const pointLight = new PointLight(0xffffff, 1)
  camera.add(pointLight)
  scene.add(camera)

  const onProgress = function (xhr) {
    if (xhr.lengthComputable) {
      const percentComplete = (xhr.loaded / xhr.total) * 100
      console.log(percentComplete.toFixed(2) + '% downloaded')
    }
  }

  new FBXLoader().load(
    props.fbxSrc,
    function (object) {
      // const size = getObjectSize(object)
      // const maxSize = Math.max(size.x, size.y, size.z)
      // const scale = 1 / maxSize
      // object.scale.setScalar(scale)
      // scene.add(object)
      // debugger

      object.traverse((child) => {
        console.log(child)
        if (child.type === 'Mesh') {
          child.material = child.material.clone()
          const edges = new EdgesGeometry(child.geometry)
          const line = new LineSegments(
            edges,
            new LineBasicMaterial({ color: 0xff0000 }), // 红色线框
          )
          child.add(line) // 将线框附加到模型上
          // console.log(child.material)
          // if (Array.isArray(child.material)) {
          //   child.material.forEach((mat) => {
          //     mat.wireframe = true
          //     mat.needsUpdate = true
          //   })
          // } else {
          //   child.material.wireframe = true
          //   child.material.needsUpdate = true
          // }
        }
        // if (child.isMesh) {
        //   // 保留原始材质
        //   child.material = child.material.clone()

        //   // 创建红色线框并叠加
        //   const edges = new THREE.EdgesGeometry(child.geometry)
        //   const line = new THREE.LineSegments(
        //     edges,
        //     new THREE.LineBasicMaterial({ color: 0xff0000 }), // 红色线框
        //   )
        //   child.add(line) // 将线框附加到模型上
        // }
      })

      const size = getObjectSize(object)
      const maxSize = Math.max(size.x, size.y, size.z)
      const scale = 1 / maxSize
      object.scale.setScalar(scale)
      scene.add(object)

      // console.log(camera.position)
      // fbx.geo
      // fbx.traverse((child) => {
      //   if (child.isMesh) {
      //     // 显示原始模型（可选）
      //     child.material = new MeshBasicMaterial({ color: 0xaaaaaa })
      //     scene.add(child)

      //     // 提取三角面片的边线
      //     const edges = new EdgesGeometry(child.geometry)
      //     const line = new LineSegments(
      //       edges,
      //       new LineBasicMaterial({ color: 0xff0000 }), // 红色边线
      //     )
      //     scene.add(line)
      //   }
      // })
    },
    onProgress,
  )

  renderer = new WebGLRenderer({ antialias: true, alpha: true })
  renderer.setPixelRatio(window.devicePixelRatio)
  renderer.setSize(window.innerWidth, window.innerHeight)
  renderer.setAnimationLoop(animate)
  containerRef.value.appendChild(renderer.domElement)

  const controls = new OrbitControls(camera, renderer.domElement)
  controls.minDistance = 0.2
  // controls.maxDistance = 50

  window.addEventListener('resize', onWindowResize)
}

// 获取模型尺寸信息
function getObjectSize(model: Object3D) {
  const box = new Box3().setFromObject(model)
  const size = box.getSize(new Vector3())
  return size
}

function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()

  renderer.setSize(window.innerWidth, window.innerHeight)
}

//

function animate() {
  renderer.render(scene, camera)
}
</script>

<style scoped lang="scss"></style>
